//
//  EarningsViewController.swift
//  btvideo
//
//  Created by mac on 2020/10/10.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyAttributes
import SwifterSwift
import MJRefresh
import SwiftyUserDefaults
import SwiftyJSON

class ST_BitianValueController: ST_BTLightBarViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title_nav_btn.setTitleForAllStates("我的积分")
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(own_navigation_bar.snp.bottom)
        }
        
        
        tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            self?.bind_data()
        })
        
        bind_data()
        
        NotificationCenter.default.addObserver(self, selector: #selector(bind_data), name: Notification.Name.modifyIncomeCoin, object: nil)
        
        main_thread_execute(afterDelay: 2) {
            self.toast_setting_wechat_number()
        }
        
    }
    
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    fileprivate func toast_setting_wechat_number(){
        
        //        男的不弹
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex != .female || Defaults[.isPanda] || ST_BTUserInfoManager.shared.additional_attributes?.wechatNumber != nil{
            return
        }
        
        let alert = BTVerticalAlertViewController.createSettingWechatAlert()
        
        alert.confirm_closure = {[weak self] in
            
            self?.footerView.push_setting_wechat_number_handle()
        }
        
        GlobalPresent(toController: alert)
        
    }
    
    @objc fileprivate func bind_data(){
        
        
        if let user = ST_BTUserInfoManager.shared.current_account_info?.userinfo {
            
            assembleData(scoring: user.income, withDraw: user.income_out)
            
        }else{
            
            assembleData(scoring: 0, withDraw: 0)
        }
        
    }
    
    
    fileprivate func assembleData(scoring:Double,withDraw:Double){
        
        let json = SCComponets.rich_text_storage_component.json["tain_value"]["header"]
        
        
        data_array = [ST_TianValueTableCellStruct.init(url: json[0]["icon"].stringValue, title: json[0]["title"].stringValue, value: String(format: "%.2f ", scoring)),ST_TianValueTableCellStruct.init(url: json[1]["icon"].stringValue, title: json[1]["title"].stringValue, value: String(format: "%.2f ", withDraw))]
        
        self.tableView.reloadData {
            self.tableView.mj_header?.endRefreshing()
        }
        
    }
    
    
    
    
    // MARK: - Properties
    
    fileprivate lazy var data_array = [ST_TianValueTableCellStruct]()
    
    fileprivate lazy var tableView:UITableView = {
        
        let control = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom + 30 , right: 0)
        
        control.delegate = self
        control.dataSource = self
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        
        
        control.register(cellWithClass: ST_TianValueTableCell.self)
        
        
        control.separatorStyle = .none
        
        control.backgroundColor = UIColor.white
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        
        //        control.tableHeaderView = self.headerView
        
        control.tableFooterView = footerView
        
        return control
    }()
    
    fileprivate lazy var footerView:ST_EarningsTableHeader = {
        let control = ST_EarningsTableHeader.init(frame: CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: ScreenWidth, height: 353+70*3)))
        return control
    }()
    
}

//MARK: - UITableViewDelegate
extension ST_BitianValueController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return data_array.count
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withClass: ST_TianValueTableCell.self, for: indexPath)
        
        cell.data = data_array[safe:indexPath.row]
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 54
    }
    
}




//MARK: - Cell
class ST_TianValueTableCell: UITableViewCell {
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.selectionStyle = .none
        
        contentView.addSubview(icon_image_view)
        contentView.addSubview(key_label)
        contentView.addSubview(value_label)
        
        
        icon_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(24)
            make.left.equalToSuperview().offset(TIANCompatibleValue(value: 15))
            make.centerY.equalToSuperview()
        }
        
        key_label.snp.makeConstraints { (make) in
            make.left.equalTo(icon_image_view.snp.right).offset(TIANCompatibleValue(value: 10))
            make.centerY.equalToSuperview()
        }
        
        
        value_label.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(TIANCompatibleValue(value: -15))
            make.centerY.equalToSuperview()
        }
        
        
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //    MARK: - Properties
    fileprivate lazy var icon_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = .scaleAspectFill
        return control
    }()
    
    
    fileprivate lazy var key_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate lazy var value_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor(hexString: "#FEC207")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium)
        return control
    }()
    
    
    var data:ST_TianValueTableCellStruct?{
        didSet{
            
            
            icon_image_view.pin_setImage(from: data?.url.url)
            
            //            icon_image_view.pin_setImage(from: data?.url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            
            key_label.text = data?.title
            
            value_label.text = data?.value
            
        }
    }
    
}


//MARK: -
struct ST_TianValueTableCellStruct {
    var url:String
    var title:String
    var value:String
}

//MARK: - Header
class ST_EarningsTableHeader: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(love_btn)
        love_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(44)
            make.width.equalTo(315)
            make.top.equalToSuperview().offset(60-15)
        }
        
        
        self.addSubview(content_button)
        content_button.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(love_btn.snp.bottom)
            make.height.equalTo(20+17+20)
        }
        
        /// 女的 已经认证成功
        guard ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female , FACE_AVATAE_STATE == 3 else{
            return
        }
        
        self.addSubview(expend_title_label)
        expend_title_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalTo(content_button.snp.bottom).offset(15)
            make.height.equalTo(22)
        }
        
        let bottomSubViews = [normal_expend_coin_view,free_chat_require_view,input_wechat_number_view,voice_expend_coin_view,video_expend_coin_view]
        
        bottomSubViews.forEach({ self.addSubview($0) })
        
        
        for (idx,item) in bottomSubViews.enumerated() {
            
            item.bind(title: jsonItems[idx]["title"].stringValue  , content: jsonItems[idx]["content"].stringValue)
            
        }
        
        
        normal_expend_coin_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(expend_title_label.snp.bottom).offset(15)
            make.height.equalTo(70)
        }
        
        
        free_chat_require_view.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(normal_expend_coin_view)
            make.top.equalTo(normal_expend_coin_view.snp.bottom)
        }
        
        input_wechat_number_view.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(normal_expend_coin_view)
            make.top.equalTo(free_chat_require_view.snp.bottom)
        }
        
        
        
        voice_expend_coin_view.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(normal_expend_coin_view)
            make.top.equalTo(input_wechat_number_view.snp.bottom)
        }
        
        
        video_expend_coin_view.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(normal_expend_coin_view)
            make.top.equalTo(voice_expend_coin_view.snp.bottom)
        }
        
        self.request_data()
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var section = SCComponets.rich_text_storage_component.json["tain_value"]["section"]
    
    fileprivate lazy var jsonItems = section["items"]
    
    
    fileprivate lazy var love_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = UIColor.init(hex: 0xFEC207)
        control.cornerRadius = 44/2.0
        control.setTitleForAllStates("积分兑换")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.setTitleColor(UIColor.white, for: UIControl.State.normal)
        control.addTarget(self, action: #selector(love_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var content_button:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        let str = "如有问题请查看".withAttributes([Attribute.font(Font.systemFont(ofSize: 12)),Attribute.textColor(UIColor.init(hex: 0xACB4C0)!)])
        
        str.append("积分帮助".withAttributes([Attribute.font(Font.systemFont(ofSize: 12)),Attribute.textColor(UIColor.init(hex: 0x3598FF)!)]))
        
        
        control.setAttributedTitle(str, for: UIControl.State.normal)
        
        control.addTarget(self, action: #selector(helpHandle), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    
    fileprivate lazy var expend_title_label:UILabel = {
        let control = UILabel.init()
        control.text = section["sectionHeaderStr"].stringValue
        control.textColor = UIColor(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate let baseTag = 1822
    
    fileprivate lazy var normal_expend_coin_view:ST_MyExpendCoinView = {
        let control = ST_MyExpendCoinView()
        control.tag = baseTag
        control.addTarget(self, action: #selector(setting_expend_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var free_chat_require_view:ST_MyExpendCoinView = {
        let control = ST_MyExpendCoinView()
        control.tag = baseTag + 3
        control.addTarget(self, action: #selector(setting_expend_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var input_wechat_number_view:ST_MyExpendCoinView = {
        let control = ST_MyExpendCoinView()
        control.addTarget(self, action: #selector(push_setting_wechat_number_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var voice_expend_coin_view:ST_MyExpendCoinView = {
        let control = ST_MyExpendCoinView()
        control.tag = baseTag + 1
        control.addTarget(self, action: #selector(setting_expend_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var video_expend_coin_view:ST_MyExpendCoinView = {
        let control = ST_MyExpendCoinView()
        control.tag = baseTag + 2
        control.addTarget(self, action: #selector(setting_expend_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate var setting_expend_control_tag:Int?
    
    fileprivate lazy var expend_picker_view:ST_BTOncePickerView = {
        
        let control = ST_BTOncePickerView()
        
        control.confirm_pick_index_closure = {[weak self] index in
            
            self?.choose_expend(index: index)
        }
        
        control.pickerFont = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
        
        return control
    }()
    
    fileprivate var normal_data_array = [ST_ChatExpendStruct]()
    
    fileprivate var intimacy_data_array = [ST_ChatExpendStruct]()
    
    fileprivate var voice_data_array = [ST_ChatExpendStruct]()
    
    fileprivate var video_data_array = [ST_ChatExpendStruct]()
    
    fileprivate func request_data(){
        
        JVrequest(PH.getTalkCoinPriceApi,success:  { (json) in
            
            let data  = json["data"]
            
            self.normal_data_array = data["talk_coin"].arrayValue.map({ST_ChatExpendStruct.init(fromJson: $0)})
            
            self.voice_data_array = data["voice_coin"].arrayValue.map({ST_ChatExpendStruct.init(fromJson: $0)})
            
            self.video_data_array = data["video_coin"].arrayValue.map({ST_ChatExpendStruct.init(fromJson: $0)})
            
            self.intimacy_data_array = data["intimacy_level"].arrayValue.map({ST_ChatExpendStruct.init(fromJson: $0)})
            
            print("打印看看数据类型：",data)
            
            self.bind_data()
            
        },failure: { (code, err) in
            
            self.parentViewController?.toast(text: err)
        })
    }
    
    fileprivate func choose_expend(index:Int){
        
        if let item = self.fetch_current_data_array()[safe:index],item.canUse{
            
            var api = PH.setTalkCoinPriceApi
            
            var param = [String:Any]()
            
            let idx = (self.setting_expend_control_tag ?? self.baseTag) - self.baseTag
            if idx == 1{
                api = PH.setVoiceTalkCoinPriceApi
                param = ["voice_coin":item.coin]
            }else if idx == 2{
                api = PH.setVideoTalkCoinPriceApi
                param = ["video_coin":item.coin]
            }else if idx == 3{
                api = PH.setFreeTalkIntimacyApi
                param = ["intimacy_id":item.id]
                
                let alert = BTVerticalAlertViewController.createChangeIntimacyConfinedAlert()
                
                alert.confirm_closure = {[weak self] in
                    self?.push_advance_setting(api: api, param: param, index: index)
                }
                
                GlobalPresent(toController: alert)
                
                return
            }else{
                
                param = ["talk_coin":item.coin]
            }
            
            push_advance_setting(api: api, param: param, index: index)
            
        }else{
            
            self.parentViewController?.toast(text: "你还没有解锁该等级，无法设置这个价格。")
        }
        
    }
    
    
    private func push_advance_setting(api:String,param:[String:Any],index:Int){
        
        
        
        JVrequest(api,parameters: param,success:  { (json) in
            
            self.fetch_current_data_array().forEach({$0.isSelected = false})
            
            self.fetch_current_data_array()[safe:index]?.isSelected = true
            
            self.bind_data()
            
        } ,failure: { (code, err) in
            
            self.parentViewController?.toast(text: err)
            
        })
        
        
        
    }
    
    fileprivate func bind_data(){
        
        if let item = self.normal_data_array.first(where: ({$0.isSelected})) {
            normal_expend_coin_view.value = item.name + "/条"
        }
        
        if let item = self.voice_data_array.first(where: ({$0.isSelected})) {
            voice_expend_coin_view.value = item.name + "/分钟"
        }
        
        if let item = self.video_data_array.first(where: ({$0.isSelected})) {
            video_expend_coin_view.value = item.name + "/分钟"
        }
        
        
        if let item = self.intimacy_data_array.first(where: ({$0.isSelected})) {
            free_chat_require_view.value = item.name
        }
        
        input_wechat_number_view.value = ST_BTUserInfoManager.shared.additional_attributes?.wechatNumber ?? "未填写"
        
    }
    
    @objc  func push_setting_wechat_number_handle(){
        
        
        
        let vc =  ST_EditInfoTextFieldController()
        
        vc.title = SCComponets.rich_text_storage_component.json["engagement_chat"]["textFieldList"][0].stringValue
        
        vc.placeholder = SCComponets.rich_text_storage_component.json["engagement_chat"]["textFieldList"][1].stringValue
        
        vc.maxLength = 30
        
        if let current = ST_BTUserInfoManager.shared.additional_attributes?.wechatNumber{
            vc.display_text = current
        }
        
        vc.update_value_closure = {[weak self] m in
            
            
            JVrequest(PH.setWeChatApi,parameters: ["wechat":m]) { (json) in
                
                
                ST_BTUserInfoManager.shared.additional_attributes?.wechatNumber = m
                
                self?.bind_data()
                
            } failure: { (code, err) in
                
                self?.parentViewController?.toast(text: err)
            }
            
            
            
            
        }
        
        
        GlobalPresent(toController: vc)
        
    }
    
    @objc fileprivate func setting_expend_handle(sender:UIView){
        
        ST_BTUserInfoManager.shared.judge_account_frozen().withUnretained(self).subscribe(onNext: { own,_ in
           
            if own.expend_picker_view.superview == nil{
                
                own.parentViewController?.view.addSubview(own.expend_picker_view)
                
                own.expend_picker_view.snp.makeConstraints { (make) in
                    make.left.bottom.right.equalToSuperview()
                    make.height.equalTo(ST_BTOncePickerView.height)
                }
            }
            
            own.expend_picker_view.isHidden = false
            
            own.setting_expend_control_tag = sender.tag
            
            let data_array = own.fetch_current_data_array()
            
            //        self.expend_picker_view.option_array = data_array.map({$0.name})
            
            guard let idx = data_array.firstIndex(where: ({$0.isSelected})) else{
                return
            }
            
            own.expend_picker_view.bind(array: data_array.map({ $0.name + $0.other }), normalIdx: idx)
            
            
            //        self.expend_picker_view.scroll_to_idx(idx)
            
            
            
        }).disposed(by: rx.disposeBag)
        
        
        
    }
    
    fileprivate func fetch_current_data_array()->[ST_ChatExpendStruct]{
        
        
        var data_array = self.normal_data_array
        
        let index = (setting_expend_control_tag ?? baseTag) - baseTag
        if index == 1{
            data_array = self.voice_data_array
        }else if index == 2{
            data_array = self.video_data_array
        }else if index == 3{
            data_array = self.intimacy_data_array
        }
        return data_array
    }
    
    @objc fileprivate func love_handle(){
        
        ST_BTUserInfoManager.shared.judge_account_frozen().withUnretained(self).subscribe(onNext: { own,_ in
            
            own.parentViewController?.navigationController?.pushViewController(ST_ConversionListViewController())
            
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    @objc fileprivate func helpHandle(){
        
        let vc = ST_BTWebViewController()
        
        vc.urlStr = PH.integralProtocolURL
        
        vc.titleStr = "\(Defaults[.PandaStr])帮助"
        
        self.parentViewController?.navigationController?.pushViewController(vc)
        
    }
}

//MARK: - Model

class ST_ChatExpendStruct : NSObject{
    
    var canUse : Bool
    var coin : Float
    var isSelected : Bool
    var name : String
    var other : String
    var id : Int
    
    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON){
        
        canUse = json["can_use"].boolValue
        coin = json["coin"].floatValue
        isSelected = json["is_selected"].boolValue
        name = json["name"].stringValue
        other = json["other"].stringValue
        
        id = json["id"].intValue
        
        super.init()
    }
}



//MARK: - Child View
class ST_MyExpendCoinView:UIControl{
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        self.addSubview(expend_content_label)
        expend_content_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(15)
            make.height.equalTo(20)
        }
        
        self.addSubview(expend_subtle_label)
        expend_subtle_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalTo(expend_content_label.snp.bottom).offset(3)
            make.height.equalTo(17)
        }
        
        self.addSubview(current_right_image_view)
        current_right_image_view.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.centerY.equalTo(expend_content_label)
        }
        
        self.addSubview(current_expend_label)
        current_expend_label.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-34)
            make.centerY.equalTo(expend_content_label)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //    MARK: - Properties
    
    fileprivate lazy var expend_content_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var expend_subtle_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor(hexString: "#ACB4C0")
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var current_expend_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor(hexString: "#ACB4C0")
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var current_right_image_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("mycenter_icon_下一页"))
        return control
    }()
    
    func bind(title:String,content:String)  {
        expend_content_label.text = title
        expend_subtle_label.text = content
    }
    
    var value = ""{
        didSet{
            current_expend_label.text = value
            
            print("设置的价格是：",value)
        }
    }
}
